package com.cynoware.busappmas.task;


import java.text.SimpleDateFormat;
import java.util.Date;

import com.cynoware.busappmas.util.GeneralUtil;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class ShowTimeThread {
	
	private TextView timeview;
	private Context context;
	private static ShowTimeThread showtimethread=new ShowTimeThread();
	private boolean isTrue=true;
	private String day="";
	private SimpleDateFormat sDateFormat= new SimpleDateFormat("HH:mm:ss");     
	public static ShowTimeThread instance(){
		return showtimethread;
	}
	
	public void init(TextView timeview,Context context){
		this.timeview=timeview;
		this.context=context;
	}

	public void start(){
		try{
			registerBoradcastReceiver();
			isTrue=true;
			new TimeThread().start();
		}catch(Exception e){
			new TimeThread().start();
		}
	}
	public void pause(){
		isTrue=false;
	}
	
	public void registerBoradcastReceiver(){  
        IntentFilter myIntentFilter = new IntentFilter();  
        myIntentFilter.addAction("copyusb");  
        context.registerReceiver(mBroadcastReceiver, myIntentFilter);  
    }  
	
	public void stop(){
		context.unregisterReceiver(mBroadcastReceiver);
	}
	
	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){  
        @Override  
        public void onReceive(Context context, Intent intent) {  
            String action = intent.getAction();  
            if(action.equals("copyusb")){  
                isTrue=false;
            }
        }  
          
    }; 
	
	public class TimeThread extends Thread{
		public void run(){
			while(isTrue){
				try {
					Thread.sleep(1000);
					Message msg=new Message();
					handler.sendMessage(msg);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
  			super.handleMessage(msg); 
  			CharSequence  TimeStr  =  sDateFormat.format(new Date());    
  			day=GeneralUtil.getWeekOfDate();
  			timeview.setText(TimeStr+"  "+day);
  			 
  		 }
	};
}
